<?php
/*
* Class teia\webdev\php\core\User
* Core class for User
*
* @author Bernardo Quibiana
* @date created: 20111006
*
* @date modified: 20111017
* @modified: Bernardo Quibiana
*/

// namespace declaration: Abstract Data Types
namespace teia\webdev\php\core;

require_once 'Item.inc';

class User {
	protected $usr_id;
	protected $usr_grp;
	protected $disp_name;
	protected $status;
	protected $db_link;
	
	/**
	 * Initialize a user object, and attemp to login if a password is specified
	 * @param string $name display name, defaults to 'Guest'
	 * @param string $usr user id (email), defaults to 'Guest'
	 * @param string $pwd password, defaults to NULL 
	 * @param string $grp user authentication group, defaults to 'Default'
	 */
	public function __construct($name='Guest', $usr='Guest', $pwd=NULL, $grp='Default') {
		//parent::__construct($grp . '_' . $usr, $usr);
		// include users database
		// proposal $db_host=localhost:3306, $db_user=admin_usr, $db_pwd=xYz_Usr_, $db_name=sec_auth
		$this->disp_name = $name;
		$this->usr_id = $usr;
		$this->usr_grp = $grp;
		$this->status = 'Guest';
		
		if ($usr && $pwd) {
			$this->login($usr, $pwd, $grp);
		} 
	} 
	
	/**
	 * Check if a given user ID is alredy registered
	 * @param string $usr_id the user ID to be checked
	 * @param string $usr_grp the user group limiting the scope of the check (optional)
	 * @param teia\webdev\php\core\MySqlLink $db_link a handler for the MySQL databse 
	 * @param string $db_tb name of the database table
	 * @param string $db_tb_usr name of the column with user IDs 
	 * @param string $db_tb_grp name of the column with user groups (optional)
	 * @return boolean true if the user ID is already registered, otherwise false
	 */
	static function verify_usr_id($usr_id, $usr_grp='Default', $db_link=NULL, $db_tb='tb_usr_auth ', $db_tb_usr='usrid', $db_tb_grp='usrgrp') {
		$result = false;
		try {
			if (!$db_link) {
				$db_link = MySqlLink::link_factory();
			}
			
			// escape values
			$usr_id = $db_link->escape_str($usr_id);
			$usr_grp = $db_link->escape_str($usr_grp);
			$db_tb = $db_link->escape_str($db_tb);
			$db_tb_usr = $db_link->escape_str($db_tb_usr);
			$db_tb_grp = $db_link->escape_str($db_tb_grp);
			
			// prepare query
			$query = "SELECT * FROM $db_tb WHERE $db_tb_usr='$usr_id' AND $db_tb_grp='$usr_grp'";
			// execute query
			$result = $db_link->verication_query($query);
		} catch (Exception $e) {
			$result = false;
		}
		return $result;
	}
	
	/**
	 * Check if a given email address is alredy registered
	 * @param string $email the email address to be checked
	 * @param string $usrGrp the user group limiting the scope of the check (optional)
	 * @param teia\webdev\php\core\MySqlLink $db_link a handler for the MySQL databse
	 * @param string $db_tb name of the database table
	 * @param string $db_tb_email name of column with email addresses
	 * @param string $db_tb_grp name of the column with user groups (optional)
	 * @return boolean true if the email address is already registered, otherwise false
	 */
	static function verify_usr_email($email, $usr_grp='Default', $db_link=NULL, $db_tb='sec_usr_auth ', $db_tb_email='email', $db_tb_grp='usr_grp') {
		$result = false;
		try {
			if (!$db_link) {
				$db_link = MySqlLink::link_factory();
			}
			// escape values
			$email = $db_link->escape_str($email);
			$usr_grp = $db_link->escape_str($usr_grp);
			$db_tb = $db_link->escape_str($db_tb);
			$db_tb_email = $db_link->escape_str($db_tb_email);
			$db_tb_grp = $db_link->escape_str($db_tb_grp);
			// preprare query
			$query = "SELECT * FROM $db_tb WHERE $db_tb_email='$email' AND $db_tb_grp='$usr_grp'";
			// execute query
			$result = $db_link->verication_query($query);
		} catch (Exception $e) {
			$result = false;
		}	
		return $result;
		
	}
	
	/**
	 * Register a user in the database
	 * @param string $usr user ID
	 * @param string $grp user group
	 * @param string $pwd user's raw password, which is encrypted using SHA1
	 * @param string $dname user's preferred name for display
	 * @param string $email user's email address
	 * @param status $status initial status of user account 
	 * @param teia\webdev\php\core\MySqlLink $db_link a handler for the MySQL databse
	 * @param string $db_tb name of the database table for user authentication
	 * @param string $db_tb_usr name of column with user IDs
	 * @param string $db_tb_grp name of column with user groups
	 * @param string $db_tb_pwd name of column with encrypted passwords
	 * @param string $db_tb_dname name of column with display names
	 * @param string $db_tb_email name of column with email addresses
	 * @param string $db_tb_status name of column with account status
	 * @return boolean return true if the registration succeeds, otherwise false
	 */
	static function register($usr, $grp='Default', $pwd , $dname, $email, $status, $db_link, $db_tb='sec_usr_auth', $db_tb_usr='usr_id', $db_tb_grp='usr_grp', $db_tb_pwd='usr_pwd',$db_tb_dname='disp_name', $db_tb_email='email',$db_tb_status='status') {
		// encrypt the password
		$sec_pwd = sha1($pwd);
		// escape values
		$usr = $db_link->escape_str($usr);
		$grp = $db_link->escape_str($grp);
		$sec_pwd = $db_link->escape_str($sec_pwd);
		$dname = $db_link->escape_str($dname);
		$email = $db_link->escape_str($email);
		$status = $db_link->escape_str($status);
		$db_tb = $db_link->escape_str($db_tb);
		$db_tb_usr = $db_link->escape_str($db_tb_usr);
		$db_tb_grp = $db_link->escape_str($db_tb_grp);
		$db_tb_pwd = $db_link->escape_str($db_tb_pwd);
		$db_tb_dname = $db_link->escape_str($db_tb_dname);
		$db_tb_email = $db_link->escape_str($db_tb_email);
		$db_tb_status = $db_link->escape_str($db_tb_status);
		// prepare query
		$query = "INSERT INTO $db_tb ($db_tb_usr,$db_tb_grp,$db_tb_pwd,$db_tb_dname,$db_tb_email,$db_tb_status) values('$usr','$grp','$sec_pwd','$dname','$email','$status')";
		// execute query
		return $db_link->verication_query($query);
	}
	
	/*
	 * instance methods
	 */
	
	/**
	 * Return the user's ID
	 */
	public function get_id() {
		return $this->usr_id;
	}
	
	/**
	 * Return the user's display name
	 */
	public function get_disp_name() {
		return $this->disp_name;	
	}
	
	/**
	 * Authenticate a user via database check
	 * @param string $usr_id the user id to be authenticated
	 * @param string $usr_pwd the raw password for the specified user id
	 * @param string $usrGrp the user group, defaults to 'Default'
	 * @param teia\webdev\php\core\MySqlLink $db_link MySqlLink object
	 * @param string $db_tb name of the table with authentication data
	 * @param string $db_tb_usr name of the column with user id data
	 * @param string $db_tb_pwd name of the column with password data
	 * @param string $db_tb_grp name of the column with group data
	 * @return boolean return true if the credentials are found in the database, otherwise false
	 */
	public function auth_user($usr_id, $usr_pwd, $usr_grp='Default', $db_link, $db_tb='sec_usr_auth ', $db_tb_usr='usr_id', $db_tb_pwd='usr_pwd', $db_tb_grp='usr_grp') {
		// encrypt password
		$sec_pwd = sha1($usr_pwd);
		// escape values
		$usr_id = $db_link->escape_str($usr_id);
		$usr_grp = $db_link->escape_str($usr_grp);
		$sec_pwd = $db_link->escape_str($sec_pwd);
		$db_tb = $db_link->escape_str($db_tb);
		$db_tb_usr = $db_link->escape_str($db_tb_usr);
		$db_tb_grp = $db_link->escape_str($db_tb_grp);
		$db_tb_pwd = $db_link->escape_str($db_tb_pwd);
		// preprare query
		$query = "SELECT * FROM $db_tb WHERE $db_tb_usr='$usr_id' AND $db_tb_grp='$usr_grp' AND $db_tb_pwd='$sec_pwd'";
		// execute query
		$result = $db_link->verication_query($query);
		
		return $result;
	}

	/**
	 * Authenticates the user against a database (wraps auth_user(...))
	 * @param string $usrId the user id to be authenticated
	 * @param string $usrPwd the password for the specified user id
	 * @param string $usrGrp the user group, defaults to 'Default'
	 */
	public function login($usr, $pwd, $grp='Default') {
		$this->status = 'Guest';
		$result = false;
		
		try {
			if (!$this->db_link) {
				$this->db_link = MySqlLink::link_factory();	
			}
			$result = $this->auth_user($usr, $pwd, $grp, $this->db_link);
			if ($result) {
				$this->db_fetch_usr_auth($usr, $grp, array('usr_id','usr_grp','disp_name'));
				$this->status = 'authenticated';
			}
		} catch (\Exception $e) {
			throw $e;
		}
		//echo MySqlLink::get_error();
		return  $result;
	}
	
	public function signup($usr, $grp='Default', $pwd , $dname, $email, $status) {
		$result = false;
		
		try {
			if (!$this->db_link) {
				$this->db_link = MySqlLink::link_factory();
			}
			$result = self::register($usr, $grp, $pwd, $dname, $email, $status, $this->db_link);
			if ($result) {
				$this->status = 'Registered';
				$this->usr_id = $usr;
				$this->usr_grp = $grp;
				$this->disp_name = $dname;
			}
		} catch (\Exception $e) {
			echo "<p>Exception: $e->getMessage()</p>\n";
			throw $e;
		}
		return  $result;
	}
	
	public function is_logged() {
		return ($this->status != 'Guest');
	}
	
	protected function db_fetch_usr_auth($usr, $grp, $fields_array=NULL) {
		if (!$this->db_link) {
			$this->db_link = MySqlLink::link_factory();
		}
		// escape values
		$usr = $db_link->escape_str($usr);
		$grp = $db_link->escape_str($grp);
		// prepare query
		$fields = ($fields_array === TRUE) ? FunctionPool::array_to_str($fields_array, ',') : 'usr_id, usr_grp, disp_name, status';
		$query = "SELECT $fields FROM sec_usr_auth WHERE usr_id='$usr' AND usr_grp='$grp' COUNT 1";
		// execute query
		$result = $this->db_link->query($query);
		if ($result === TRUE && is_resource($result)) {
			$result_row = mysql_fetch_assoc($result);
			foreach ($result_row as $key => $value) {
				@$this->$key = $value;	// suppress errors on undefined properties
			}
		}
	} 
}	// end of User class

?>